package com.shiwenping.reply.net.body;

import android.text.TextUtils;

import java.io.File;
import java.lang.reflect.Field;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author shiwenping
 * @date 17-11-9 下午12:14
 */

public class BaseBody {
    private final BaseBody baseBody = setBody();

    private BaseBody setBody() {
        return this;
    }

    public MultipartBody build() {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        Class claszz = this.baseBody.getClass();
        do {
            Field[] fields = claszz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    if (field.get(this.baseBody) == null || TextUtils.isEmpty(String.valueOf(field.get(this.baseBody)))) {
                        continue;
                    }
                    if (field.getType().getName().equals(File.class.getName())) {
                        File file = (File) field.get(this.baseBody);
                        builder.addFormDataPart(field.getName(), file.getName(), RequestBody.create(MediaType.parse("*/*"), file));
                    } else {
                        builder.addFormDataPart(field.getName(), String.valueOf(field.get(this.baseBody)));
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            break;
        } while (claszz != Object.class);
        return builder.build();
    }
}
